const express = require('express');
const router = express.Router();
const {User} = require('../../models');
const {Op} = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { Success, failure } = require('../../utils/responses');

//获取所有用户列表
router.get('/', async (req, res) => {
    try {
        const query = req.query;
        //分页查询需要的参数
        const currentPage = Math.abs(query.currentPage) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [["id", "DESC"]],
            offset: offset,
            limit: pageSize
        };
        //模糊搜索
        if (query.email) {
            condition.where = {
                email: {
                    [Op.eq]: query.email
                }
            };
        }

        if (query.username) {
            condition.where = {
                username: {
                    [Op.eq]: query.username
                }
            };
        }

        if (query.nickname) {
            condition.where = {
                nickname: {
                    [Op.like]: `%${ query.nickname }%`
                }
            };
        }

        if (query.role) {
            condition.where = {
                role: {
                    [Op.eq]: query.role
                }
            };
        }


        const users = await User.findAndCountAll(condition);
        Success(res, '用户查询成功', {
            rows: users.rows,
            pagination: {
                total: users.count,
                currentPage: currentPage,
                pageSize: pageSize
            }
        });
    } catch (err) {
        failure(res, err);
    }
});
//获取指定用户
router.get('/:id', async (req, res) => {
    try {

        const user = await GetUser(req);
        Success(res, '获取用户成功', user);
    } catch (err) {
        failure(res, err);
    }
});
//创建用户
router.post('/', async (req, res) => {
    try {

        //白名单过滤
        const body = FilterBody(req);
        const user = await User.create(body);

        Success(res, '创建用户成功', user, 201);
    } catch (error) {
        console.log("错误信息：", error);

        failure(res, error);

    }
});
//更新用户
router.put('/:id', async (req, res) => {
    try {
        const user = await GetUser(req);
        await user.update(req.body);
        Success(res, '更新成功！', user, 200)
    } catch (err) {
        failure(res, err);
    }
});




/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{password, role: (number|string|*), introduce: ({type: *}|*), sex: (number|*), nickname: (string|*), company: ({type: *}|*), avatar: ({type: *, validate: {isUrl: {msg: string}}}|*), email: (string|*), username}}
 */
function FilterBody(req) {
    return {
        email: req.body.email,
        username: req.body.username,
        password: req.body.password,
        nickname: req.body.nickname,
        sex: req.body.sex,
        company: req.body.company,
        introduce: req.body.introduce,
        role: req.body.role,
        avatar: req.body.avatar
    };
}

//获取user对象
async function GetUser(req) {
    const {id} = req.params;
    console.log(id);
    const user = await User.findByPk(id);
    if (!user) {
        throw new NotFoundError(`ID:${id}的用户未找到`);
    }
    return user;
}

module.exports = router;